﻿/// <reference path="parseUri.js" />
/// <reference path="processing.js" />
"use strict";

// click page action to start cleaning process
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.start == true) {
        start();
    }
});

var actionsToDo = ['remove_comment','remove_content']; // what actions to perform
var fb_dtsg = ""; //a constant, not sure why FB needs it, but it's included in every fb's post requests


var log = function (msg) {
	/// <summary>
	/// logging. Update this to have better way to show progress to users
	/// </summary>
    /// <param name="msg">
    /// message to log
    /// </param>
    console.log(msg);
};

var simulateClick = function (element) {
	/// <summary>
	/// simulate a click 
	/// </summary>
    /// <param name="element">
    /// the element to receive the click event
    /// </param>
    var event = document.createEvent("MouseEvents");
    event.initEvent('click', true, true);

    log("clicking .. " + $(element).toString());
    element.dispatchEvent(event);
}


var getEditButtons = function getEditButtons(monthElement) {
	/// <summary>
	/// get list of edit buttons (the little pencil buttons).
	/// </summary>
    /// <param name="monthElement">
    /// the month element that was clicked to show all stories in that month
    /// </param>
	/// <returns type=""></returns>
    return $("div#" + getCorrespondingBlockIdOnTimeline(monthElement) +" ul li a[aria-label] i");
}

var IsAjaxifyElementActionable = function IsAjaxifyElementActionable() {
	/// <summary>
    /// filter out any hyperlinks that do not 
    /// perform an action
	/// </summary>
	/// <returns type="boolean"> </returns>
    var uriData = parseUri("https://facebook.com" + $(this).attr("ajaxify"));

    return uriData.file === "take_action_on_story.php";
}

var getDTSG = function () {
	/// <summary>
	/// get fb_dtsg to include in POST request
	/// </summary>
	/// <returns type=""></returns>
    return $('input[name="fb_dtsg"]').first().attr("value");
};


var getYearMonthFromTimelineLink = function (monthElement) {
    var tmp = $(monthElement).attr('href').split("/");
    var lastIdx = tmp.length - 1;
    return { "year": tmp[lastIdx - 1], "month": tmp[lastIdx] };
}

var getCorrespondingBlockIdOnTimeline = function (monthElement) {
    var yearMonth = getYearMonthFromTimelineLink(monthElement);
    return "month_" + yearMonth.year + "_" + yearMonth.month;
}

var performAction = function (element) {
    /// <summary>
    /// post an request to clean up the story associated 
    /// with the given element
    /// </summary>
    /// <param name="element">
    /// an ajaxify element that is associated with an action
    /// </param>
    /// <returns type=""></returns>
    var deferred = new $.Deferred();

    var uriData = parseUri("https://facebook.com" + $(element).attr("ajaxify"));
    var data = {
        'fb_dtsg': fb_dtsg,
        'confirmed': "true",
        'ban_user': '0'
    };

    // only perform actions specified in actionsToDo list
    if ($.inArray(uriData.queryKey['action'], actionsToDo) > -1) {
        log("perform: " + uriData.queryKey['action']);
        log("element = " + $(element).toString());
        for (var key in uriData.queryKey) {
            data[key] = uriData.queryKey[key];
        }

        $.ajax({
            type: "POST",
            url: "https://www.facebook.com/ajax/timeline/take_action_on_story.php",
            data: data,
            complete: function (jqXHR, settings) {
                deferred.resolve();
                if (jqXHR.status === 200) {
                    log("successfully delete one item: " + jqXHR);
                }
            }
        });
    }
    else {
        deferred.resolve();
    }

    return deferred;
};


function getAjaxifyElements(editButton) {
    /// <summary>
    /// Ajaxify elements are exposed only when the corresponding edit button is clicked
    /// </summary>
    /// <param name="editButton">
    /// the edit button that was clicked to expose all actions associated with the story
    /// </param>
    /// <returns type=""></returns>

    var parentElement = $(editButton).parent().parent();
    var actionableAjaxifyElements = parentElement.find('a[ajaxify]').filter(IsAjaxifyElementActionable);

    return actionableAjaxifyElements;
}

function getEditButtons(monthElement) {
    /// <summary>
    /// get list of edit buttons (the little pencil buttons).
    /// </summary>
    /// <param name="monthElement">
    /// the month element that was clicked to show all stories in that month
    /// </param>
    /// <returns type=""></returns>
    return $("div#" + getCorrespondingBlockIdOnTimeline(monthElement) + " ul li a[aria-label] i");
}

function getMonthElements(yearElement) {
    var $elements = $(yearElement).parent().find("> ul > li[data-key] > a");
    log("found " + $elements.length + " month elements");
    return $elements;
}


function getYearElements() {
    /// <summary>
    /// Geting all the year elements in the right column
    /// </summary>
    /// <returns type=""></returns>
    var $elements = $("ul.fbTimelineScrubber li[data-year]>a");
    log("found " + $elements.length + " year elements");
    return $elements;
}

function start() {
    console.log("Starting ...");
    fb_dtsg = getDTSG();
    log("fb_dtsg = " + fb_dtsg);

    process({
        Generator: getYearElements,
        ActionOnItem: simulateClick,
        Next: {
            Generator: getMonthElements,
            ActionOnItem: simulateClick,
            Next: {
                Generator: getEditButtons,
                ActionOnItem: simulateClick,
                Next: {
                    Generator: getAjaxifyElements,
                    ActionOnItem: performAction
                }
            }
        }
    }, null , function () {
        log("done!done!done!");
    });
}

jQuery.fn.toString = function () {
    return $(this).clone().wrap('<div/>').parent().html();
};




